package de.jmda.sample.mproc.task;

import static de.jmda.core.mproc.ProcessingUtilities.getFiler;
import static de.jmda.core.mproc.ProcessingUtilities.isProcessingOver;
import static de.jmda.core.util.CollectionsUtil.asSet;
import static de.jmda.core.util.StringUtil.sb;
import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.io.Writer;
import java.util.Set;

import javax.tools.JavaFileObject;

import org.junit.Test;

import de.jmda.core.mproc.task.AbstractTypeElementsTaskTypes;
import de.jmda.core.mproc.task.TaskException;
import de.jmda.core.mproc.task.TaskRunner;

public class JUTTypeElementsTaskProcessingRounds
{
	private class TypeElementsTask extends AbstractTypeElementsTaskTypes
	{
		private int round = 0;
		private boolean produce;

		public TypeElementsTask(Set<? extends Class<?>> types, boolean produce)
    {
	    super(types);
	    this.produce = produce;
    }

		@Override
		public boolean execute() throws TaskException
		{
			StringBuffer sb = sb("round: " + round + ", produce: " + produce);

			round++;

			if (produce)
			{
				try
				{
					JavaFileObject javaFileObject = getFiler().createSourceFile("EmptyClass");
					Writer writer = javaFileObject.openWriter();
					writer.append("class EmptyClass {}");
					writer.close();
					sb.append(", produced file");
//					sb.append(", produced file " + javaFileObject.toUri());
				}
				catch (IOException e)
				{
					throw new TaskException("failure creating source file", e);
				}

				produce = false;
			}
			
			if (isProcessingOver())
			{
				sb.append(", last round - goodbye");
			}
			
			System.out.println(sb);

			return false;
		}
	}

	@Test
	public void testProduceFalse() throws IOException
	{
		TypeElementsTask task = new TypeElementsTask(asSet(String.class), false);

		TaskRunner.run(task);

		assertEquals("wrong number of rounds", 2, task.round);
	}

	@Test
	public void testProduceTrue() throws IOException
	{
		TypeElementsTask task = new TypeElementsTask(asSet(String.class), true);

		TaskRunner.run(task);
		
		assertEquals("wrong number of rounds", 3, task.round);
	}
}